<?php
/**
 * 解析XML相关
 * @author xnny
 * @version 
 */


/**
 * 解析XML相关
 * @author wangtao
 *
 */
class wt_xml3
{
	/**
	 * 读取RSS并判断
	 * @access public
	 * @param string $rss	RSS源地址
	 * @return void
	 */
	static function readRSS($rss)
	{
		set_time_limit(0);
		$d = get_headers($rss, 1);
		$d = strpos($d[0], '200');
		#$d = fopen($rss, 'r');
		if ($d)
		{
			$xml = file($rss);
			switch (self::getDomain($rss))
			{
				case 'feedburner.com':return self::readFeedburnerRSS($xml, $rss);
				default:return self::loadRSS($xml, $rss);
			}
		}
		else
		{
			Log::writeLog($rss . '----------' . '连接失败！---'. date('Y.m.d H:i:s') . "\n");
		}
	}

	/**
	 * 将RSS内博客信息相关存入数组$arr
	 * @access public
	 * @param string $rss	RSS源地址
	 * @return void
	 */
	static function readInfo($rss)
	{
		set_time_limit(0);
		$xml = simplexml_load_file($rss);
		foreach($xml -> children() as $child)
		{
			$arr["title"] = (string)($child -> title);#博客标题
			$arr["lastBuildDate"] = date('Y-m-d H:i:s', strtotime((string)($child -> pubDate)));#博客最后更新时间
			if (empty($arr["lastBuildDate"]))
			{
				$arr["lastBuildDate"] = date('Y-m-d H:i:s', strtotime((string)($child -> lastBuildDate)));#博客最后更新时间
			}
			$arr["link"] = (string)($child -> link);#博客链接
			$arr["description"] = (string)($child -> description);#博客简介
		}
		$arr['feed'] = $rss;
		return $arr;
	}

	/**
	 * 处理Feedburner订阅器
	 * 
	 * @access public
	 * @param array 	$xml
	 * @param string	$rss
	 * @return array
	 */
	static function readFeedburnerRSS($xml, $rss)
	{
		set_time_limit(0);
		$data = implode('', $xml);
		#创建XML解析器
		$parser = xml_parser_create();
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    	xml_parse_into_struct($parser, $data, $values, $tags);
    	xml_parser_free($parser);
    	
    	//print_r($tags);
    	//if (isset($tags))
		#博客標題
    	if (isset($tags['title']))
    	{
    		isset($values[$tags['title'][0]]['value']) ? $blogTitle = $values[$tags['title'][0]]['value'] : $blogTitle = null;
    	}
    	else
    	{
    		$blogTitle = null;
    	}    	
		#博客鏈接
    	if (isset($tags['link']))
    	{
    		isset($values[$tags['link'][0]]['attributes']['href']) ? $blogLink = $values[$tags['link'][0]]['attributes']['href'] : $blogTitle = null;
    	}
    	else
    	{
    		$blogLink = null;
    	}
    	#博客備註
    	if (isset($tags['subtitle']))
    	{
    		isset($values[$tags['subtitle'][0]]['value']) ? $blogDescription = $values[$tags['subtitle'][0]]['value'] : $blogDescription = null;  
    	}
    	else
    	{
    		$blogDescription = null;
    	}
	    #博客最新更新日期
    	if (isset($tags['updated']))
    	{
    		isset($values[$tags['updated'][0]]['value']) ? $blogPubDate = date('Y-m-d H:i:s', strtotime($values[$tags['updated'][0]]['value'])) : $blogPubDate = null;
    	}
    	else
    	{
    		$blogPubDate = null;
    	}
    	
    	#获得RSS相关信息
    	// 遍历 XML 结构
	    foreach ($tags as $key=>$val) 
    	{
    		//如果是博文信息
        	if ($key == 'entry' || $key == 'item')
        	{
        		$table['post'] = self::selectXMLKey($val, $values, $rss);
        	}
			else
			{
            	continue;
        	}
    	}
    	#插入RSS信息
    	foreach ($table['post'] as $key => $value)
    	{
    		$table['post'][$key]['pubDate'] = date('Y-m-d H:i:s', strtotime($table['post'][$key]['pubDate']));
    		//$table['post'][$key]['published'] = self::feedburnerTime($table['post'][$key]['published']);
    		$table['post'][$key]['feed'] = $rss;
    	}
    	#加入博客信息
    	$table['info']['title'] = $blogTitle;//博客標題
    	$table['info']['link'] = $blogLink;//博客鏈接
    	$table['info']['Description'] = $blogDescription;//博客簡介
    	$table['info']['PubDate'] = $blogPubDate;//博客更新日期
    	$table['info']['feed'] = $rss;
    	return $table; //返回 最终的数组
	}
	

	/**
	 * 处理RSS
	 * 
	 * @access public
	 * @param array 	$xml
	 * @param string	$rss
	 * @return array
	 */
	static function loadRSS($xml, $rss)
	{
		set_time_limit(0);
		$data = implode('', $xml);
		#创建XML解析器
    	$parser = xml_parser_create();
    	xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
    	xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
    	xml_parse_into_struct($parser, $data, $values, $tags);
    	xml_parser_free($parser);
    	
    	#博客標題
    	if (isset($tags['title']))
    	{
    		isset($values[$tags['title'][0]]['value']) ? $blogTitle = $values[$tags['title'][0]]['value'] : $blogTitle = null;
    	}
    	else
    	{
    		$blogTitle = null;
    	}
    	#博客鏈接
    	if (isset($tags['link']))
    	{
    		isset($values[$tags['link'][0]]['value']) ? $blogLink = $values[$tags['link'][0]]['value'] : $blogLink = null;
    	}
    	else
    	{
    		$blogLink = null;
    	}
    	#博客備註
    	if (isset($tags['description']))
    	{
    		isset($values[$tags['description'][0]]['value']) ? $blogDescription = $values[$tags['description'][0]]['value'] : $blogDescription = null;
    	}
    	else
    	{
    		$blogDescription = null;
    	}
    	#博客最新更新日期
    	if (isset($tags['pubDate']))
    	{
    		isset($values[$tags['pubDate'][0]]['value']) ? $blogPubDate = date('Y-m-d H:i:s', strtotime($values[$tags['pubDate'][0]]['value'])) : $blogPubDate = null;
    	}
    	else
    	{
    		$blogPubDate = null;
    	}
    	#博客語言
    	if (isset($tags['language']))
    	{
    		isset($values[$tags['language'][0]]['value']) ? $blogLanguage = $values[$tags['language'][0]]['value'] : $blogLanguage = 'zh-cn';
    	}
    	else
    	{
    		$blogLanguage = 'zh-cn';
    	}

    	// 遍历 XML 结构
    	foreach ($tags as $key=>$val) 
    	{
    		//保存文章
        	if ($key == 'item')
        	{
        		$table['post'] = self::selectXMLKey($val, $values);
        	}
			else
			{
            	continue;
        	}
    	}
    	
		if (isset($table['post']))
		{
			foreach ($table['post'] as $key => $value)
			{
				#方便存入数据库，进行日期转换
				$table['post'][$key]['pubDate'] = date('Y-m-d H:i:s', strtotime($table['post'][$key]['pubDate']));
				// wt_time::Str2time($table['post'][$key]['pubDate']);
				$table['post'][$key]['feed'] = $rss;	
    		}
		}
		else
		{
			die($rss);
		}
    	
    	#加入博客信息
    	$table['info']['title'] = $blogTitle;
    	$table['info']['link'] = $blogLink;
    	$table['info']['Description'] = $blogDescription;
    	$table['info']['PubDate'] = $blogPubDate;
    	$table['info']['language'] = $blogLanguage;
    	$table['info']['feed'] = $rss;

    	return $table; //返回 最终的数组
	}

	/**
	 * 选取RSS节点
	 * @param $val
	 * @param $values
	 */
	static function selectXMLKey($val, $values)
	{
		set_time_limit(0);
		$molranges = $val;
	    $t = count($molranges);
        for ($i=0; $i < $t; $i+=2)
        {
           	$offset = $molranges[$i] + 1;
           	$len = $molranges[$i + 1] - $offset;
           	$tdb[] = self::parseMol(array_slice($values, $offset, $len));
        }
        return $tdb;
	}

	static function parseMol($mvalues)
	{
		set_time_limit(0);
		$t = count($mvalues);
    	for ($i=0; $i < $t; $i++)
    	{
			switch($mvalues[$i]["tag"])
			{
				case 'dc:creator' : $mvalues[$i]['tag'] = 'dc_creator';break;
				case 'content:encoded' : $mvalues[$i]['tag'] = 'content_encoded';break;
				case 'slash:comments' : $mvalues[$i]['tag'] = 'slash_comments';break;
				case 'wfw:commentRss' : $mvalues[$i]['tag'] = 'wfw_commentRss';break;
				
				case 'name' : $mvalues[$i]['tag'] = 'dc_creator';break;
				case 'content' : $mvalues[$i]['tag'] = 'content_encoded';break;
				case 'feedburner:origLink' : $mvalues[$i]['tag'] = 'link';break;
				case 'updated' : $mvalues[$i]['tag'] = 'pubDate';break;
				case 'thr:total' : $mvalues[$i]['tag'] = 'wfw_commentRss';break;
			}
			if(isset($mvalues[$i]['value']))
			{
				$mol[$mvalues[$i]['tag']] = $mvalues[$i]['value'];
			}
    	}
    return $mol;
	}

	/**
	 * 取得RSS的域名
	 * @access public
	 * @param string $rss		RSS源地址
	 * 
	 * @return string
	 */
	static function getDomain($rss)
	{
		set_time_limit(0);
		preg_match('/^(http:\/\/)?([^\/]+)/i', $rss, $matches);
		$host = $matches[2];
		preg_match('/[^\.\/]+\.[^\.\/]+$/', $host, $matches);
		if (isset($matches[0]))
		{
			return $matches[0];
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 加入博文
	 * @access public
	 * @param array $p		文章
	 * @param int	$BID	博文ID
	 * @return void
	 */
	static function addPost($p, $BID)
	{
		set_time_limit(0);
		#开始存入数据
		$db = mysqlDB::con();

		$postCreator = empty($p['dc_creator']) ? empty($p['author']) ? self::getDomain($p['feed']) : $p['author'] : $p['dc_creator'];
		$postContent = empty($p['content_encoded']) ? $p['description'] : $p['content_encoded'];
		$slashComments = empty($p['slash_comments']) ? 0 : $p['slash_comments'];
		$sql = 'INSERT INTO `feed`.`post_into` (`Pid` ,`Post_Title` ,`Post_Link` ,`Post_PubDate` ,`Post_Creator` ,
		`Post_Content` ,`BID`) VALUES (NULL ,\'' . addslashes($p['title']) . '\',\'' . addslashes($p['link']) . 
		'\',\'' . $p['pubDate'] . '\',\'' . addslashes($postCreator) . '\',\'' . addslashes($postContent) . 
		'\',\'' . $BID . '\')';
		$db->query($sql);
		$strPosr = $p['title'] . ' => is OK. | link => ' . $p['link'] . ' | Time:' . date('Y-m-d H:i:s') . "\n";
		Log::writeLog($strPosr);
		//echo '更新成功';
	}
	
	/**
 	* 得到最后更新时间
 	* @param string $feed 源
 	*/
	static function getLastUpdate($feed)
	{
		set_time_limit(0);
		$db = mysqlDB::con();
		$sql = 'SELECT `Blog_LastBuildDate` FROM `blog_info` WHERE 1 AND `Blog_Feed` = \'' . $feed . '\' LIMIT 0 , 1';
		return strtotime($db->query2one($sql));
	}
	
	/**
	 * 得到源的ID
	 * @param string $feed  源
	 */
	static function getBlogID($feed)
	{
		set_time_limit(0);
		$db = mysqlDB::con();
		$sql = 'SELECT `BID` FROM `blog_info` WHERE 1 AND `Blog_Feed` = \'' . $feed . '\' LIMIT 0 , 1';
		return $db->query2one($sql);
	}
}